package com.jtjrenren.android.taxi.driver.core.user.login;


import com.jtjrenren.android.taxi.driver.bean.event.DriverTypeEvent;
import com.jtjrenren.android.taxi.driver.bean.event.LoginEvent;
import com.jtjrenren.android.taxi.driver.bean.DriverInfo;
import com.jtjrenren.android.taxi.driver.manger.AppManger;
import com.jtjrenren.android.taxi.driver.utils.ModuleUtils;
import com.library.mvp.presenter.MvpBasePresenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

/**
 * Created by Administrator on 2016/8/18.
 */

public class LoginPresenterImpl extends MvpBasePresenter<LoginView, LoginInterctor> implements LoginPresenter {
    private DriverInfo currentDriver;

    public LoginPresenterImpl(LoginView view) {
        super(view);
    }


    @Override
    public LoginInterctor createInteractor() {
        return new LoginInterctorImpl();
    }


    @Subscribe
    public  void handGetTypeEvent(DriverTypeEvent typeEvent) {
        DriverInfo info = typeEvent.getInfo();
        if (info == null || currentDriver == null) {
            loginError();
            return;
        }

        currentDriver.setDriverType(info.getDriverType());
        currentDriver.setDriverChildType(info.getDriverChildType());
        currentDriver.setTerminalType(info.getTerminalType());

        AppManger.getInstance().loginSuccess(view.getContext(), currentDriver);
        view.hideLoadding();
        view.loginSuccess();
    }


    @Subscribe
    public void handLoginEvent(LoginEvent loginEvent) {
        DriverInfo info = loginEvent.getInfo();
        if (info == null) {
            loginError();
            return;
        }
        currentDriver = info;
        getDriverType(info.getWorkNo());
    }

    private void loginError() {
        view.hideLoadding();
        view.showTip("登录失败，请检查账号或者密码是否正确");
    }

    @Override
    public void init() {
        EventBus.getDefault().register(this);
    }

    @Override
    public void destory() {
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void login(String phone, String pwd) {
        //首先检验手机和密码的正确性,然后密码加密
        String desc = ModuleUtils.checkPhone(phone);
        if (desc != null) {
            view.showTip(desc);
            return;
        }
        desc = ModuleUtils.checkPwd(pwd);
        if (desc != null) {
            view.showTip(desc);
            return;
        }

        String pwdjm = ModuleUtils.DesEncry(pwd);
        view.showLoadding("登录中，请稍候");
        interactor.login(phone, pwdjm);
    }

    @Override
    public void getDriverType(String driverID) {
        interactor.getDriverType(driverID);
    }

}
